package com.nowcoder.community.controller;

import com.nowcoder.community.config.WkConfig;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.pojo.Event;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Api(description = "分享长图相关")
@Controller
public class ShareController implements CommunityConstant{

    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkhtmltoimage;

    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;

    @ApiOperation(value = "分享长图到七牛云")
    @GetMapping("/share")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "htmlUrl", value = "html长图的的url")
    })
    public String share(String htmlUrl){
        //文件名
        String fileName = CommunityUtil.generateUUID();

        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl", htmlUrl)
                .setData("fileName", fileName)
                .setData("suffix", ".png");

        eventProducer.fireEvent(event);

        //返回访问路径
        Map<String , Object> map = new HashMap<>();
//        map.put("shareUrl", domain + contextPath + "/share/image/" + fileName);
        map.put("shareUrl", shareBucketUrl + "/" + fileName);

        return CommunityUtil.getJSONString(0, null, map);//页面上显示上传的路径（在map中）
    }



    //废弃
    @ApiOperation(value = "获取长图（已废弃）")
    @GetMapping("/share/image/{fileName}")
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response){
        if(StringUtils.isBlank(fileName)){
            throw new RuntimeException("文件名不能为空！");
        }

        response.setContentType("image/png");

        File file = new File(wkhtmltoimage + "/" + fileName + ".png");


        //try...with...resource
        try (
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file)
                ){
            byte[] buff = new byte[1024];
            int len = 0;

            while((len = fis.read(buff)) != -1){
                os.write(buff, 0, len);
            }
        } catch (IOException e) {
            logger.error("获取长图失败:" + e.getMessage());
        }


    }
}
